//
//  ViewController.swift
//  Rouyu
//
//  Created by 李雷川 on 2017/5/24.
//  Copyright © 2017年 李雷川. All rights reserved.
//

import UIKit
import WebKit
import SnapKit
import CoreBluetooth

class ViewController: UIViewController {
    var webView:WKWebView!
    var pointIndex = 0
    var timer:Timer?
    var isTouchBegin = false;
    var infoLabel: UILabel!
    var textView: UITextView!
    var data =  Data()
    fileprivate var drawButton: UIButton!
    fileprivate var evaluateButton: UIButton!
    fileprivate var openButton: UIButton!
    fileprivate var closeButton: UIButton!
    var resultLabel: UILabel!
    var centralManager:CBCentralManager!
    var discoveredPeripheral:CBPeripheral!
    fileprivate let drawView = FZKaiShuDrawView(frame: CGRect.init(x: 84, y: 614, width: 600, height: 600))
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        initBluetooth()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func initUI(){
     
        infoLabel = UILabel()
        infoLabel.textColor = UIColor.lightGray
        infoLabel.text = "蓝牙未打开"
        view.addSubview(infoLabel)
        
        openButton = UIButton(type: .custom)
        openButton.setTitle("打开蓝牙", for: .normal)
        openButton.setTitleColor(UIColor.blue, for: .normal)
        openButton.addTarget(self, action: #selector(tapOpen(_:)), for: .touchUpInside)
        openButton.isHidden = true;
        view.addSubview(openButton)
        
        closeButton = UIButton(type: .custom)
        closeButton.isEnabled = false;
        closeButton.setTitle("关闭蓝牙", for: .normal)
        closeButton.isHidden = true
        closeButton.setTitleColor(UIColor.blue, for: .normal)
        closeButton.addTarget(self, action: #selector(tapClose(_:)), for: .touchUpInside)
        view.addSubview(closeButton)
        
        textView = UITextView()
        textView.textColor = UIColor.black
        view.addSubview(textView)
        
        webView = WKWebView.init(frame: CGRect.zero, configuration: WKWebViewConfiguration())
        webView.backgroundColor = UIColor.red
        view.addSubview(webView)

        let bundlePath =  Bundle.main.bundlePath
        let urlPath = bundlePath.appending("/evaluation/index.html")
        let request = URLRequest(url: URL.init(fileURLWithPath: urlPath))
        webView.load(request)
        
        drawButton = UIButton(type: .custom)
        drawButton.setTitle("开始绘制", for: .normal)
        drawButton.setTitleColor(UIColor.blue, for: .normal)
        drawButton.addTarget(self, action: #selector(tapDraw(_:)), for: .touchUpInside)
        view.addSubview(drawButton)
        
        evaluateButton = UIButton(type: .custom)
        evaluateButton.isEnabled = false;
        evaluateButton.setTitle("评测", for: .normal)
        evaluateButton.setTitleColor(UIColor.blue, for: .normal)
        evaluateButton.addTarget(self, action: #selector(tapEvaluate(_:)), for: .touchUpInside)
        view.addSubview(evaluateButton)
        
        
        resultLabel = UILabel()
        resultLabel.textColor = UIColor.black
        resultLabel.text = "评测结果:"
        view.addSubview(resultLabel)
        resultLabel.isHidden = true
        resultLabel.numberOfLines = 0
        
        
        drawView.handwritingType = .langhao
        drawView.p_setBrushWidth(11)
        drawView.p_setBrush(UIColor.black)
        drawView.backgroundColor = UIColor.red
        view.addSubview(drawView)
        
        
        infoLabel.snp.makeConstraints { (make) in
            make.top.equalTo(84)
            make.centerX.equalTo(view)
        }
        openButton.snp.makeConstraints { (make) in
            make.top.equalTo(infoLabel.snp.bottom).offset(8)
            make.right.equalTo(view.snp.centerX).offset(-8)
        }
        closeButton.snp.makeConstraints { (make) in
            make.top.equalTo(infoLabel.snp.bottom).offset(8)
            make.left.equalTo(view.snp.centerX).offset(8)
        }
        textView.snp.makeConstraints { (make) in
            make.top.equalTo(openButton.snp.bottom).offset(8)
            make.leading.trailing.equalTo(view)
            make.height.equalTo(88)
        }
        
        webView.snp.makeConstraints { (make) in
            make.top.equalTo(textView.snp.bottom).offset(8)
            make.centerX.equalTo(self.view)
            make.size.equalTo(300)
        }
        
        drawButton.snp.makeConstraints { (make) in
            make.top.equalTo(webView.snp.bottom).offset(24)
            make.right.equalTo(self.view.snp.centerX).offset(-12)
        }
        evaluateButton.snp.makeConstraints { (make) in
            make.top.equalTo(webView.snp.bottom).offset(24)
            make.left.equalTo(drawButton.snp.right).offset(36)
        }
        resultLabel.snp.makeConstraints { (make) in
            make.top.equalTo(drawButton.snp.bottom).offset(24)
            make.centerX.equalTo(self.view.snp.centerX)
            make.width.equalTo(self.view).multipliedBy(0.8)
        }
    }
    
    
 
    func startTimer(){
        if(timer == nil){
            timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(doStep), userInfo: nil, repeats:true)
        }
        timer?.fireDate = NSDate.distantPast
        
    }
    
    func doStep(){
        guard pointIndex < points.count else {
            timer?.fireDate = NSDate.distantFuture
            pointIndex = 0
            evaluateButton.isEnabled = true
            return;
        }
        let point = points[pointIndex]
        if(point.event == 65){
            if(isTouchBegin){
                doTouchMove(point: point)
            }else{
                isTouchBegin = true
                resultLabel.isHidden = true
                evaluateButton.isEnabled = false
                doTouchBegin(point: point)
            }
            
        }else if(point.event == 66){
            isTouchBegin = false
            doTouchEnd(point: point)
        }else{
            
        }
        pointIndex  = pointIndex + 1
    }
    
    //打开蓝牙
    func tapOpen(_ sender: Any) {
    }
    
    //关闭蓝牙
    func tapClose(_ sender: Any) {
    }
    
    
    func tapDraw(_ sender: Any) {
        clear()
        let bundlePath =  Bundle.main.bundlePath
        do{
            let jsonPath =  bundlePath.appending("/evaluation/test.json")
            let content = try String.init(contentsOfFile: jsonPath)
            webView.evaluateJavaScript("setCharacter(\(content))") { (response, error) in
            }
            
            let board = "setBoard(140, 370, 180, 600)"
            webView.evaluateJavaScript("\(board)") { (response, error) in
            }
            
        }catch{
            debugPrint("error")
        }
        startTimer()
        
    }
    
    func tapEvaluate(_ sender: Any){
        let clear = "evaluate()"
        webView.evaluateJavaScript("\(clear)") { [unowned self](response, error) in
            debugPrint("error is \(String(describing: error))")
            self.resultLabel.isHidden = false
            self.resultLabel.text = "评测结果:\(String(describing: response))"
        }
    }
    
    
    
    func clear(){
        let clear = "clearBoard()"
        webView.evaluateJavaScript("\(clear)") { (response, error) in

        }
    }
    
    
    
    
    func doTouchBegin(point:(event:Int,x:Int,y:Int,z:Int)){
        drawView.draw(with: CGPoint.init(x: point.x, y: point.y), state: .began, andTimestamp: 1.0)
        
        let point = "penDown(\(point.x),\(point.y))"
        webView.evaluateJavaScript("\(point)") { (response, error) in
            
        }
    }
    
    func doTouchMove(point:(event:Int,x:Int,y:Int,z:Int)){
        drawView.draw(with: CGPoint.init(x: point.x, y: point.y), state: .changed, andTimestamp: 1.0)
        let point = "penMove(\(point.x),\(point.y))"
        webView.evaluateJavaScript("\(point)") { (response, error) in
            
        }
    }
    
    func doTouchEnd(point:(event:Int,x:Int,y:Int,z:Int)){
        drawView.draw(with: CGPoint.init(x: point.x, y: point.y), state: .ended, andTimestamp: 1.0)
        let point = "penUp(\(point.x),\(point.y))"
        webView.evaluateJavaScript("\(point)") { (response, error) in
        }
    }
    
}



